package org.idea.qiyu.framework.threadpool.dynamic.executor;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.idea.qiyu.framework.threadpool.dynamic.config.QiyuDynamicThreadPoolProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @Author linhao
 * @Date created in 3:32 下午 2021/10/26
 */
@Configuration
public class QiyuExecutorConfigListener {


    @Resource
    private QiyuDynamicThreadPoolProperties qiyuDynamicThreadPoolProperties;

    @PostConstruct
    public void init(){
        this.initConfigUpdateListener();
    }


    public void initConfigUpdateListener(){
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
        properties.put(PropertyKeyConst.NAMESPACE, "qiyu-test");
        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            configService.addListener("qiyu-framework-threadpool-dynamic.properties", "DEFAULT_GROUP", new Listener() {
                @Override
                public Executor getExecutor() {
                    return Executors.newSingleThreadExecutor();
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.printf("configInfo is %s",configInfo);
                    qiyuDynamicThreadPoolProperties.getExecutors();
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

}
